package com.gluxen.util;

import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.aspectj.weaver.patterns.ThisOrTargetAnnotationPointcut;

import com.gluxen.controller.WeixinController;
import com.gluxen.po.*;
import com.sun.media.jfxmedia.track.VideoResolution;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressWarnings("deprecation")
public class weixinUtil {
	//我的订阅号
	//public static final String APPID="wxad0e6a4ce7071d2a";
	//private static final String APPSECRET="2d10747dc1340e980a645b17e418fe42";
	
	//小姜测试号
	//private static final String APPID="wx53ae0ab51f76d777";
	//private static final String APPSECRET="112979ca9f34a83a6761dc47aa8feea5";
	
	//我的测试号
<<<<<<< HEAD
	//public static final String APPID="wxb87f3d63ac2672f7";
	//private static final String APPSECRET="52863399b381074e9e6b1e707205cbac";
	
	//农行企业服务号
	public static final String APPID= "wx0f4cc2f827e27614";
	private static final String APPSECRET="ec2f62765c6c8d9da03f7c19a6155d21";
=======
	public static final String APPID="wxb87f3d63ac2672f7";
	private static final String APPSECRET="52863399b381074e9e6b1e707205cbac";
	
	//农行企业服务号
	//public static final String APPID= "wx0f4cc2f827e27614";
	//private static final String APPSECRET="ec2f62765c6c8d9da03f7c19a6155d21";
>>>>>>> lichangqing
	
	private static final String ACCESS_TOKEN_URL="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
	private static final String UPLOAD_URL="https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
	private static final String UPLOAD_URL_FOREVER = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
	private static final String UPLOAD_PICTEXT = "https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=ACCESS_TOKEN";
	private static final String CREATE_MENU_RUL="https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
	private static final String DELETE_MENU_RUL="https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=ACCESS_TOKEN";
	private static final String SENDMESSAGE_URL="https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=ACCESS_TOKEN";
	private static final String HEADIMAGEURL="https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
	
	private static final String GET_AUTOREPLY = "https://api.weixin.qq.com/cgi-bin/get_current_autoreply_info?access_token=ACCESS_TOKEN";
	private static long preTime = 0;
	private  static AccessToken token;
	
	/**GET请求
	 * 功能：用GET方式执行传入的url，获取执行url后接收到的信息，将信息转为String，再转为JSONObject格式返回。
	 * @param url
	 * @return
	 */
	//需要jar包：json-lib-2.4-jdk15.jar，这个jar包依赖于五个jar包commons-beanutils-1.8.3.jar，commons-collections-3.2.1.jar，commons-logging-1.1.1.jar，ezmorph-1.0.6.jar
	//共六个jar包
	public static JSONObject doGetStr(String url){
		
		//需要导入jar包：httpclient-4.5.jar，httpcore-4.4.1.jar
		DefaultHttpClient httpclient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		JSONObject jsonObject = null;
		
		try {
			HttpResponse response = httpclient.execute(httpGet);
			HttpEntity entity = response.getEntity();
			if(entity!=null){
				String resultString = EntityUtils.toString(entity,"utf-8");
				jsonObject = JSONObject.fromObject(resultString);
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return jsonObject;
	}
	
	/**post请求
	 * 功能：用POST方式执行传入的url（之前将url信息outStr封装），获取执行url后接收到的信息，将信息转为String，再转为JSONObject格式返回。
	 * @param url outStr
	 * @return
	 */
	public static JSONObject doPostStr(String url, String outStr){
		DefaultHttpClient httpclient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(url);
		JSONObject jsonObject = null;
		try {
			httpPost.setEntity(new StringEntity(outStr,"utf-8"));
			HttpResponse response = httpclient.execute(httpPost);
			String resultString = EntityUtils.toString(response.getEntity(),"utf-8");
			jsonObject = JSONObject.fromObject(resultString);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonObject;
	}
	
	/**
	 * 获取access_token
	 * 注意：微信公众账号access_token的获取次数不能超过2000次
	 * 如果每次都从微信平台获取的话可能会超过2000次，因此最好把access_token保存到本地
	 * 一个access_token有两个小时的有效期
	 * 一个access_token过期后才获取新的access_token
	 * 这样一天只需要获取12次，不会超过2000次的限制
	 * @return
	 */
	public static AccessToken getAccessToken(){
		long nowTime = new Date().getTime();
		if(nowTime-preTime>=3600000){//超过一个小时就取一次。
			token = new AccessToken();
			String url = ACCESS_TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);
			JSONObject jsonObject = doGetStr(url);
			if(jsonObject!=null){
				token.setToken(jsonObject.getString("access_token"));
				token.setExpiresIn(jsonObject.getInt("expires_in"));
			}
			preTime = nowTime;
			return token;
		}else 
			return token;
	}
	

	
//	public static AccessToken getAccessToken(){
//		AccessToken token = new AccessToken();
//		String url = ACCESS_TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);
//		JSONObject jsonObject = doGetStr(url);
//		if(jsonObject!=null){
//			//System.out.println("jsonObject:"+jsonObject.toString());
//			token.setToken(jsonObject.getString("access_token"));
//			token.setExpiresIn(jsonObject.getInt("expires_in"));
//		}
//		return token;
//	}

	public static String SendMessage(String token,String message){

		String url = SENDMESSAGE_URL.replace("ACCESS_TOKEN",token);
		JSONObject jsonObject = doPostStr(url,message);
		return jsonObject.getString("errcode");
	}

	public static String upload_pictext(String picText,String accessToken) throws IOException{
		String purl = UPLOAD_PICTEXT.replace("ACCESS_TOKEN",accessToken);
		JSONObject jsonObject = doPostStr(purl,picText);
//		if(jsonObject == null){
//			return jsonObject.getString("errcode");
//		}

		return jsonObject.getString("errcode");
	}





	/**
	 * 处理文件上传,并获取medieID
	 * @param filePath
	 * @param accessToken
	 * @param type
	 * @return
	 * @throws IOException 
	 * 参考慕课网，java中的文件上传下载。
	 */
	public static String upload(String filePath,String accessToken,String type) throws IOException{
		File file = new File(filePath);
		if(!file.exists()||!file.isFile()){
			throw  new IOException("文件不存在！");
		}
		//上传临时素材
		String url = UPLOAD_URL.replace("ACCESS_TOKEN", accessToken).replace("TYPE", type);
		//上传永久素材。
		//String url = UPLOAD_URL_FOREVER.replace("ACCESS_TOKEN", accessToken).replace("TYPE", type);
		URL urlObj = new URL(url);
		
		//连接
		HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
		connection.setRequestMethod("POST");
		connection.setDoInput(true);
		connection.setDoOutput(true);
		connection.setUseCaches(false);
		
		//设置请求头信息
		String BOUNDRY = "----------"+System.currentTimeMillis();
		
		connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+BOUNDRY);
		StringBuilder sBuilder = new StringBuilder();
		sBuilder.append("--");
		sBuilder.append(BOUNDRY);
		sBuilder.append("\r\n");
		sBuilder.append("Content-Disposition:form-data;name=\"file\";filename=\""+file.getName()+"\"\r\n");
		sBuilder.append("Content-Type:application/octet-stream\r\n\r\n");
		
		byte[] head = sBuilder.toString().getBytes("utf-8");
		
		//获得输出流
		OutputStream out = new DataOutputStream(connection.getOutputStream());
		//输出表头
		out.write(head);
		
		//文件正文部分，把文件以流的方式推入到url中。
		DataInputStream in = new DataInputStream(new FileInputStream(file));
		int bytes = 0;
		byte[] bufferOut = new byte[1024];
		while((bytes=in.read(bufferOut))!=-1){
			out.write(bufferOut,0,bytes);
		}
		in.close();
		
		//结尾部分
		byte[] foot = ("\r\n--"+BOUNDRY+"\r\n").getBytes("utf-8");//定义最后的数据分割线
		
		out.write(foot);
		
		out.flush();
		out.close();
		
		
		StringBuffer buffer = new StringBuffer();
		BufferedReader reader = null;
		String result = null;
		
		//定义bufferedReader 输入流来读取URL的响应。
		reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
		String line = null;
		while((line = reader.readLine())!= null){
			buffer.append(line);
		}
		if(result==null){
			result=buffer.toString();
		}
		reader.close();
		
		JSONObject jsonObject = JSONObject.fromObject(result);
		System.out.println(jsonObject);
		
		return jsonObject.getString("media_id");
	}
	
	public static String upload2(String filePath,String accessToken,String type) throws IOException{
		File file = new File(filePath);
		if(!file.exists()||!file.isFile()){
			throw  new IOException("文件不存在！");
		}
		String url = UPLOAD_URL_FOREVER.replace("ACCESS_TOKEN", accessToken).replace("TYPE", type);
		URL urlObj = new URL(url);

		//连接
		HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
		connection.setRequestMethod("POST");
		connection.setDoInput(true);
		connection.setDoOutput(true);
		connection.setUseCaches(false);

		//设置请求头信息
		String BOUNDRY = "----------"+System.currentTimeMillis();

		connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+BOUNDRY);
		StringBuilder sBuilder = new StringBuilder();
		sBuilder.append("--");
		sBuilder.append(BOUNDRY);
		sBuilder.append("\r\n");
		sBuilder.append("Content-Disposition:form-data;name=\"media\";filename=\""+file.getName()+"\"\r\n");
		sBuilder.append("Content-Type:application/octet-stream\r\n\r\n");

		byte[] head = sBuilder.toString().getBytes("utf-8");

		//获得输出流
		OutputStream out = new DataOutputStream(connection.getOutputStream());
		//输出表头
		out.write(head);

		//文件正文部分，把文件以流的方式推入到url中。
		DataInputStream in = new DataInputStream(new FileInputStream(file));
		int bytes = 0;
		byte[] bufferOut = new byte[1024];
		while((bytes=in.read(bufferOut))!=-1){
			out.write(bufferOut,0,bytes);
		}
		in.close();

		//结尾部分
		byte[] foot = ("\r\n--"+BOUNDRY+"\r\n").getBytes("utf-8");//定义最后的数据分割线

		out.write(foot);

		out.flush();
		out.close();


		StringBuffer buffer = new StringBuffer();
		BufferedReader reader = null;
		String result = null;

		//定义bufferedReader 输入流来读取URL的响应。
		reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
		String line = null;
		while((line = reader.readLine())!= null){
			buffer.append(line);
		}
		if(result==null){
			result=buffer.toString();
		}
		reader.close();

		JSONObject jsonObject = JSONObject.fromObject(result);
		System.out.println(jsonObject);

		return jsonObject.getString("media_id");
	}








	/**
	 * 创建自定义菜单。
	 * @param token
	 * @param menu
	 * @return
	 * 测试在test文件中
	 */
	public static int createMenu(String token,String menu){
		int result = 0;
		String url = CREATE_MENU_RUL.replace("ACCESS_TOKEN", token);
		JSONObject jsonObject = doPostStr(url, menu);
		if(jsonObject!=null){
			result = jsonObject.getInt("errcode");
		}
		return result;
	}
	
	/**
	 * 删除自定义菜单
	 * @param token
	 * @return
	 */
	public static int deleteMenu(String token){
		int result = 0;
		String url = DELETE_MENU_RUL.replace("ACCESS_TOKEN", token);
		JSONObject jsonObject = doGetStr(url);
		if(jsonObject!=null){
			result = jsonObject.getInt("errcode");
		}
		return result;
	}




	public static String Get_code(String redirect_uri){
		String appid = "wx53ae0ab51f76d777";
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri="+redirect_uri+"&response_type=code&scope="+"snsapi_base"+"&state=123#wechat_redirect";
		return url;
	}


	public static String Get_Openid(String code){
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
		String Get_Openid = url.replace("APPID",APPID).replace("SECRET",APPSECRET).replace("CODE",code);
		JSONObject jsonObject = doGetStr(Get_Openid);
		String openid = jsonObject.getString("openid");
		return openid;
	}
	
	public static String Get_headImageUrl(String code,String openId){
		String url = HEADIMAGEURL.replace("ACCESS_TOKEN",getAccessToken().getToken()).replace("OPENID",openId);
		JSONObject jsonObject = doGetStr(url);
		String headImageUrl=jsonObject.getString("headimgurl");
		return headImageUrl;
	}

	
	/**
	 * 从接口得到自动回复规则的json字符串。
	 * @return
	 */
	public static String Get_autoReply_json(){
		String url = GET_AUTOREPLY.replace("ACCESS_TOKEN",getAccessToken().getToken());
		JSONObject jsonObject = doGetStr(url);
		return jsonObject.toString();
	}
	/**
	 * 根据接口初始化自动回复规则类。
	 * @return
	 */
	public static AutoReply init_autoReply(){
		//测试获取自动回复规则
		String autoReplyStr = weixinUtil.Get_autoReply_json();
		JSONObject obj=JSONObject.fromObject(autoReplyStr);
				
		Map<String,Class<?>> map = new HashMap<String,Class<?>>();
		//子类可以代替父类,可以转化为一个对象前提是字符串中的值都能在对象中找到对应的位置，对象中位置比较多的情况下也能成功。
		map.put("list", AutoReply_new.class);
		map.put("keyword_list_info", AutoReply_KeyWord.class);
		map.put("reply_list_info", AutoReplyMessage_news.class);
		//将规则封装为一个实体类。
		AutoReply autoReply = (AutoReply)JSONObject.toBean(obj,AutoReply.class,map);//指定转换的类型，但仍需要强制转化-成功
		return autoReply;
	}
	
	/**
	 * 根据关键字从自动回复规则中找出消息体，并封装成xml格式的字符串返回
	 * @param toUserName
	 * @param fromUserName
	 * @param content
	 * @return
	 */
	public static String get_autoreply_message(String toUserName,String fromUserName,String content){
		String message = null;
		
		AutoReply autoReply = WeixinController.autoReply;
		
		Autoreply_keyword_info keyword_info = autoReply.getKeyword_autoreply_info();
		List<AutoReply_Rule> list = keyword_info.getList();
		
		for(AutoReply_Rule ar :list){
			List<AutoReply_KeyWord> keyword_list_info = ar.getKeyword_list_info();
			for(AutoReply_KeyWord ak:keyword_list_info){
				//如果是精确匹配且与关键字相等，或者是contain匹配且包含关键字，则匹配成功。
				if((ak.getMatch_mode().equals("equal")&&ak.getContent().equals(content))||(ak.getMatch_mode().equals("contain")&&content.indexOf(ak.getContent())>=0)){
					List<AutoReplyMessage> reply_list_info = ar.getReply_list_info();
					//匹配成功后判断为图文消息。
					if(reply_list_info.get(0).getType().equals("news")){
						//回复类型是图文。
						List<News> newsList = new ArrayList<News>();
						NewsMessage newsMessage = new NewsMessage();
						AutoReplyMessage_news news= (AutoReplyMessage_news)reply_list_info.get(0);
						AutoReply_news news_info = news.getNews_info();
						List<AutoReply_new> list2 = news_info.getList();
						
						for(int i = 0;i<list2.size();i++){
							AutoReply_new new1 = list2.get(i);
							News news1 = new News();
							
							news1.setTitle(new1.getTitle());
							news1.setDescription(new1.getDigest());
							news1.setPicUrl(new1.getCover_url());
							news1.setUrl(new1.getSource_url());
							newsList.add(news1);
						}
						newsMessage.setToUserName(fromUserName);
						newsMessage.setFromUserName(toUserName);
						newsMessage.setCreateTime(new Date().getTime());
						newsMessage.setMsgType(MessageUtil.MESSAGE_NEWS);
						newsMessage.setArticles(newsList);
						newsMessage.setArticleCount(newsList.size());
						message = MessageUtil.newsMessageToXml(newsMessage);
						return message;
					}else if(reply_list_info.get(0).getType().equals("text")){
						//自动回复文本。
						TextMessage text1 = new TextMessage();
						
						text1.setFromUserName(toUserName);
						text1.setToUserName(fromUserName);
						text1.setMsgType(MessageUtil.MESSAGE_TEXT);
						text1.setCreateTime(new Date().getTime());
						text1.setContent(reply_list_info.get(0).getContent());
				
						message = MessageUtil.TextToMessage(text1);
						return message;
					}else if(reply_list_info.get(0).getType().equals("img")){
						//自动回复对象
						ImageMessage imageMessage = new ImageMessage();
						
						Image image = new Image();
						image.setMediaId(reply_list_info.get(0).getContent());
						
						imageMessage.setFromUserName(toUserName);
						imageMessage.setToUserName(fromUserName);
						imageMessage.setCreateTime(new Date().getTime());
						imageMessage.setMsgType(MessageUtil.MESSAGE_IMAGE);
						imageMessage.setImage(image);
						
						return MessageUtil.imageMessageToXml(imageMessage);
					}else if(reply_list_info.get(0).getType().equals("voice")){
						//自动回复语音。
						VoiceMessage vm = new VoiceMessage();
						
						Voice voice = new Voice();
						voice.setMediaId(reply_list_info.get(0).getContent());
						
						vm.setToUserName(toUserName);
						vm.setFromUserName(fromUserName);
						vm.setCreateTime(new Date().getTime());
						vm.setVoice(voice);
						vm.setMsgType("voice");
						
						return MessageUtil.voiceMessageToXml(vm);
					}else if(reply_list_info.get(0).getType().equals("video")){
						//自动回复视频
						VideoMessage videoM = new VideoMessage();
						Video v = new Video();
						
						v.setMediaId(reply_list_info.get(0).getContent());
						//通过接口获取的video信息只有一个mediaId，并没有标题或者描述，但是给微信用户发送的时候xml格式，需要有这两项，所以就随便玩了。
						v.setDescription("描述");
						v.setTitle("标题");
						
						videoM.setCreateTime(new Date().getTime());
						videoM.setFromUserName(fromUserName);
						videoM.setToUserName(toUserName);
						videoM.setMsgType("video");
						videoM.setVideo(v);
						
						return MessageUtil.videoMessageToXml(videoM);
					}
				}
			}
		}
		return MessageUtil.initTextMessage(toUserName, fromUserName, autoReply.getMessage_default_autoreply_info().getContent());
	}
}


